package com.weilan.blog.admin.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weilan.blog.admin.entity.SysAdmin;
import com.weilan.blog.admin.entity.SysRole;
import com.weilan.blog.admin.service.SysAdminService;
import com.weilan.blog.admin.service.SysRoleService;
import com.weilan.blog.common.global.SQLConf;
import com.weilan.blog.common.global.SysConf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 将SpringSecurity中的用户管理和数据库的管理员对应起来
 *
 * @author 陌溪
 * @date 2020/9/14 10:43
 */
@Service
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysAdminService sysAdminService;

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * @param username 浏览器输入的用户名【需要保证用户名的唯一性】
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.USER_NAME, username);
        queryWrapper.last(SysConf.LIMIT_ONE);
        SysAdmin sysAdmin = sysAdminService.getOne(queryWrapper);
        if (sysAdmin == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            //查询出角色信息封装到admin中
            List<String> roleNames = new ArrayList<>();
            SysRole role = sysRoleService.getById(sysAdmin.getRoleUid());
            roleNames.add(role.getRoleName());
            sysAdmin.setRoleNames(roleNames);
            return SecurityUserFactory.create(sysAdmin);
        }
    }
}
